package com.liu.shop.config;

import com.liu.shop.common.constant.OrderConstatns;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    // 1.创建一个订单业务交换机
    @Bean
    public TopicExchange orderExchange(){
        // 交换机名字，开启持久化，不是自动删除
        return new TopicExchange(OrderConstatns.ORDER_EXCHANGE,true,false);
    }

    // 2.创建订单延时队列，订单在一段时间未支付后就会变成订单超时状态
    @Bean
    public Queue orderDelayQueue(){
        Map<String, Object> args = new HashMap<>();
        args.put("x-message-ttl",1000*60*3); //消息在队列中等待3分钟
        args.put("x-dead-letter-exchange", OrderConstatns.ORDER_DLE_EXCHANGE); // 3分钟后跳转到死信交换机
        args.put("x-dead-letter-routing-key", "order.dle.ttl"); // 死信路由键
        return new Queue(OrderConstatns.ORDER_TTL_QUEUE, true, false, false, args);
    }

    // 3.将订单交换机和订单延时队列进行绑定
    @Bean
    public Binding orderTtlQueueBind() {
        return BindingBuilder.bind(orderDelayQueue()).to(orderExchange()).with("order.*");
    }

    // 1.创建死信交换机
    @Bean
    public TopicExchange orderDleExchange() {
        return new TopicExchange(OrderConstatns.ORDER_DLE_EXCHANGE, true, false);
    }

    // 2，订单超时创建死信队列
    @Bean
    public Queue orderTtlDelQueue() {
        return new Queue(OrderConstatns.ORDER_TTL_DLE_QUEUE, true, false, false);
    }

    // 3.死信交换机和死信队列绑定
    @Bean
    public Binding orderTtlDelQueueBind() {
        return BindingBuilder.bind(orderTtlDelQueue()).to(orderDleExchange()).with("order.dle.*");
    }

    // 1.订单超时，库存队列
    @Bean
    public Queue stockTtlUnlockQueue(){
        Map<String, Object> args = new HashMap<>();
        args.put("x-message-ttl", 1000 * 60 * 4); // 4m
        args.put("x-dead-letter-exchange", OrderConstatns.ORDER_DLE_EXCHANGE); // 死信交换机
        args.put("x-dead-letter-routing-key", "stock.dle.ttl"); // 死信路由键
        return new Queue(OrderConstatns.STOCK_TTL_UNLOCK_QUEUE,true,false,false,args);
    }

    // 2.订单交换机和库存释放队列绑定
    @Bean
    public Binding stockTtlUnlockQueueBind(){
        return BindingBuilder.bind(stockTtlUnlockQueue()).to(orderExchange()).with("order.*");
    }

    // 库存死信队列
    @Bean
    public Queue stockDleUnlockQueue(){
        return new Queue(OrderConstatns.STOCK_DLE_UNLOCK_QUEUE,true,false,false);
    }

    // 库存死信队列和订单死信交换机绑定
    @Bean
    public Binding stockDleUnlockBind(){
        return BindingBuilder.bind(stockDleUnlockQueue()).to(orderDleExchange()).with("stock.dle.*");
    }

}
